<template>
  <div class="app-container">
    <div class="form-cont">
      <el-tabs
        class="form"
        v-model="headertype"
        style="float: none"
        @tab-click="handleTabClick"
      >
        <el-tab-pane label="出售中商品" name="csz"> </el-tab-pane>
        <el-tab-pane label="仓库中商品" name="ckz"> </el-tab-pane>
        <el-tab-pane label="已经售空商品" name="sk"> </el-tab-pane>
        <el-tab-pane label="警戒商品" name="jj"> </el-tab-pane>
        <el-tab-pane label="商品回收站" name="sphs"> </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品搜索" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类">
        <el-cascader
          :options="categoryOption"
          :props="{ checkStrictly: true }"
          v-model="selectedIds"
          @change="handleCascaderChange"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openForm()"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :loading="exportLoading"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="商品分类">
              <span>{{ getCategoryNames(props.row.cateId) }}</span>
            </el-form-item>
            <el-form-item label="市场价">
              <span>{{ props.row.otPrice }}</span>
            </el-form-item>
            <el-form-item label="成本价">
              <span>{{ props.row.cost }}</span>
            </el-form-item>
            <el-form-item label="虚拟销量">
              <span>{{ props.row.ficti }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="商品图" align="center" prop="image" width="100"
        ><template slot-scope="scope">
          <image-preview
            :src="scope.row.image"
            :width="50"
            :height="50"
          /> </template
      ></el-table-column>
      <el-table-column
        label="商品名称"
        prop="storeName"
        width="300px"
        show-overflow-tooltip
      />
      <el-table-column label="商品售价" align="center" prop="price" />
      <el-table-column label="销量" align="center" prop="sales" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="添加时间" align="center" width="150px">
        <template #default="scope">
          {{ scope.row.createTime | formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShow"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="onchangeIsShow(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="150px"
        class-name="small-padding fixed-width"
      >
        <template v-slot="scope">
          <el-button size="mini" type="text" @click="openUpdateForm(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="recyclebin(scope.row.id)"
            v-if="
              headertype === 'csz' ||
              headertype === 'ckz' ||
              headertype === 'sk' ||
              headertype === 'jj'
            "
            >加入回收站</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="restore(scope.row.id)"
            v-if="headertype === 'sphs'"
            >恢复商品</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-if="headertype === 'sphs'"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import * as ProductApi from "@/api/store/storeproduct";
import * as CategoryApi from "@/api/store/category";
import ProductForm from "./ProductForm.vue";
export default {
  name: "Product",
  components: {
    ProductForm,
  },
  data() {
    return {
      // 分类 ID 和分类名称的映射
      categoryIdMap: {},
      //存储商品分类下拉框选中的id
      selectedIds: [],
      //分类列表数据
      categoryList: [],
      //级联选择器所需的层级数据
      categoryOption: [],
      //头部导航
      headertype: "csz",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        storeName: null,
        cateId: null,
        isShow: 1,
        stock: 2,
        isRecycle: 0,
      },
    };
  },
  created() {
    //获取分类数据
    CategoryApi.getCategoryList((this.status = 1)).then((res) => {
      this.categoryList = res.data;
      // 转换数据为级联结构
      this.categoryOption = this.buildCascaderOptions(this.categoryList);
      this.buildCategoryIdMap(this.categoryList);
      this.getList();
    });
  },
  methods: {
    //恢复商品
    restore(id) {
      const updateData = {
        id: id,
        isRecycle: 0
      };
      ProductApi.updateProduct(updateData).then((res) => {
        this.$modal.msgSuccess("恢复商品成功");
        this.handleTabClick();
      });
    },
    //加入回收站
    recyclebin(id) {
      const updateData = {
        id: id,
        isRecycle: 1
      };
      ProductApi.updateProduct(updateData).then((res) => {
        this.$modal.msgSuccess("加入回收站成功");
        this.handleTabClick();
      });
    },
    //根据分类ID数组获取名称
    getCategoryNames(cateIdStr) {
      if (!cateIdStr) return "";
      return cateIdStr
        .split(",")
        .map((id) => this.categoryIdMap[id])
        .join(" 、 ");
    },
    // 构建分类 ID 和分类名称的映射
    buildCategoryIdMap(categoryList) {
      categoryList.forEach((category) => {
        this.categoryIdMap[category.id] = category.name;
        if (category.children && category.children.length > 0) {
          this.buildCategoryIdMap(category.children);
        }
      });
    },
    //获取级联选择器选中的值
    handleCascaderChange(ids) {
      // 仅当选中最后一级时有效（根据业务需求判断）
      const finalId = ids[ids.length - 1];
      if (finalId) {
        this.queryParams.cateId = finalId;
      }
    },
    /**
     * 构建级联选择器所需的层级结构
     */
    buildCascaderOptions(list) {
      // 1. 筛选顶级分类（pid=0）
      const rootCategories = list.filter((category) => category.pid === 0);
      // 2. 递归构建子分类
      const buildChildren = (parentId, level = 1) => {
        // 获取当前层级的子分类
        const children = list
          .filter((category) => category.pid === parentId)
          .map((category) => {
            // 构建基础结构
            const option = {
              value: category.id,
              label: category.name,
            };

            // 只在第一级和第二级构建子分类
            // 对于第三级，不构建更深的层级
            if (level < 3) {
              // 递归查找子分类
              const childOptions = buildChildren(category.id, level + 1);
              // 只有当子分类存在时才添加children属性
              if (childOptions && childOptions.length > 0) {
                option.children = childOptions;
              }
            }
            return option;
          });
        return children;
      };
      // 3. 组装顶级分类及其子分类
      return rootCategories.map((category) => {
        const option = {
          value: category.id,
          label: category.name,
        };
        // 构建第一级的子分类
        const children = buildChildren(category.id, 1);
        // 只有当子分类存在时才添加children属性
        if (children && children.length > 0) {
          option.children = children;
        }
        return option;
      });
    },
    // 状态变更
    onchangeIsShow(row) {
      const updateData = {
        id: row.id,
        isShow: row.isShow
      };
      ProductApi.updateProduct(updateData).then((res) => {
        this.$modal.msgSuccess("状态更新成功");
        this.handleTabClick();
      });
    },
    // 导航栏切换
    handleTabClick() {
      if (this.headertype == "csz") {
        this.queryParams.isShow = 1;
        this.queryParams.stock = 2;
      } else if (this.headertype == "ckz") {
        this.queryParams.isShow = 0;
        this.queryParams.stock = 2;
      } else if (this.headertype == "sk") {
        this.queryParams.stock = 0;
      } else if (this.headertype == "sphs") {
        this.queryParams.isRecycle = 1;
      } else if (this.headertype == "jj") {
        this.queryParams.stock = 1;
      }
      this.getList();
      this.queryParams.stock = null;
      this.queryParams.isShow = null;
      this.queryParams.isRecycle = 0;
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await ProductApi.getProductPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.handleTabClick();
    },
    /** 重置按钮操作 */
    resetQuery() {
      //清空商品分类下拉框中的数据
      this.selectedIds = [];
      //清除分类id
      this.queryParams.cateId = null;
      //清除搜索栏数据
      this.resetForm("queryForm");
      //执行搜索
      this.handleQuery();
    },
    /** 添加操作 */
    openForm() {
      this.$router.push({ name: "productForm"});
    },
    /**修改操作 */
    openUpdateForm(id){
      this.$router.push({ name: "updateProductForm", params: { id: id} });
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm(
        '是否确认删除商品编号为"' + id + '"的数据项?'
      );
      try {
        await ProductApi.deleteProduct(id);
        this.handleTabClick();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm("是否确认导出所有商品管理数据项?");
      try {
        this.exportLoading = true;
        const data = await ProductApi.exportProductExcel(this.queryParams);
        this.$download.excel(data, "商品管理.xls");
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
  },
};
</script>
<style>
.demo-table-expand {
  margin-left: 100px;
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
